from odoo import api, models, fields, exceptions
from odoo.exceptions import UserError



class NbdProjectTask(models.Model):
    _inherit = ["project.task"]

    name = fields.Char(string="项目名称", placeholder='项目名称...', required=True)
    project_no = fields.Char(string="项目ID", placeholder='项目ID...', required=True)
    project_start_date = fields.Date(string="项目启动日期", required=True,default=lambda self: fields.Date.today())
    project_type = fields.Char(string="项目类型",required=True)
    business_value = fields.Text(string="业务价值", required=True)
    expected_investment = fields.Text(string="预计投入",required=True)
    main_risks = fields.Text(string="主要风险",required=True)
    project_source = fields.Char(string="项目来源", size=20)
    cooperation_model = fields.Text(string="合作模式")
    cooperation_type = fields.Selection([
        ('1', "M&A"),
        ('2', "license-in"),
        ('3', "Distribution-to-Acquisition"),
        ('4', "JV"),
        ('5', "MAH"),
        ('6', "divest"),
        ('7', "other"),
    ], string="项目类型", required=True)
    project_leader_id = fields.Many2one('res.users',
                                        string='项目负责人',
                                        default=lambda self: self.env.user,
                                        create=False,  # 禁止创建新用户
                                        ondelete='restrict',  # 当用户被删除时，限制删除
                                        required=True
                                        )
    project_leader_dept = fields.Many2one('hr.department', string='负责部门',
                                          readonly=True,compute='_compute_department_id')
    project_context = fields.Text(string="项目背景", placeholder='项目背景信息...')
    tar_name = fields.Char(string="标的公司名称", required=True, size=100)
    tar_address = fields.Char(string="标的公司地址", size=100)
    company_profile = fields.Text(string="公司简介", size=512)
    legal_representative = fields.Char(string="法定代表人", size=50)
    registered_capital = fields.Char(string="注册资本", size=50)
    website = fields.Char(string="官网", size=10)
    establishment_date = fields.Date(string="成立时间")
    unified_social_credit_code = fields.Char(string="统一社会信用代码", required=True, size=18)
    main_contact_name = fields.Char(string="主要联系人", required=True, size=50)
    main_contact_phone = fields.Char(string="主要联系人电话", size=11)
    main_contact_email = fields.Char(string="主要联系人邮箱", size=50)
    other_contact_name = fields.Char(string="其他联系人", size=50)
    other_contact_phone = fields.Char(string="其他联系人电话", size=11)
    other_contact_email = fields.Char(string="其他联系人邮箱", size=50)
    NDA_status = fields.Char(string="NDA签署状态")
    checklist_status = fields.Char(string="CheckList进度")
    BusinessCase_status = fields.Selection([
        ('1', "未开始"),
        ('2', "进行中"),
        ('3', "已完成"),
    ], string="Business Case进度")
    Contract_status = fields.Selection([
        ('1', "未开始"),
        ('2', "进行中"),
        ('3', "已完成"),
    ], string="合同进度")
    item_type_file_ids = fields.One2many(
        comodel_name='nbd.filemanager',
        inverse_name='task_id',
        string='附件'
    )
    tarcompany_ids = fields.One2many(
        comodel_name='nbd.tarcompany',
        inverse_name='task_id',
        string='标的公司'
    )
    product_ids = fields.One2many(
        comodel_name='nbd.productinfo',
        inverse_name='task_id',
        string='标的产品',
        required=True
    )
    review_ids = fields.One2many(
        comodel_name='nbd.internalreview',
        inverse_name='id',
        string='回顾会议关联'
    )
    DD_ids = fields.One2many(
        comodel_name='nbd.duediligence',
        inverse_name='task_id',
        string='尽调关联'
    )
    team_user_ids = fields.Char(string="参与者")
    
    nda_state = fields.Selection([
        ('1', "未开始"),
        ('2', "进行中"),
        ('3', "已完成"),
    ], string="NDA签署状态")
    
    dd_checklist_state = fields.Selection([
        ('1', "未开始"),
        ('2', "进行中"),
        ('3', "已完成"),
    ], string="CheckList进度")
    
    @api.model
    def get_default_project_id(self):
        temp_project_id = self.env['project.project'].search([('name', '=', 'NBD Default Project')],limit=1).sudo()
        if temp_project_id :
            temp_context = self.env.context.copy()
            temp_context.update({'default_project_id' : temp_project_id.id}) 
            self.with_context(temp_context)
            return temp_project_id.id
        else:
            return None
        


    @api.depends('stage_id')
    def isinvisible_prev(self):
        self.compute_is_readonly()
        if not self.project_id:
            self.project_id = self.get_default_project_id()
        try:
            for rec in self:
                if not rec.stage_id or rec.stage_id.name == "立项":
                    rec.is_invisible_prev = 1
                else:
                    rec.is_invisible_prev = 0
        except Exception:
            self.is_invisible_prev = 1
    
    
    @api.depends('stage_id')
    def isinvisible_next(self):
        if not self.project_id:
            self.project_id = self.get_default_project_id() 
        try:
            for rec in self:
                if not rec.stage_id or rec.stage_id.name == "Completed":
                    rec.is_invisible_next = 1
                else:
                    rec.is_invisible_next = 0
        except Exception:
            self.is_invisible_next = 1
            
            
    @api.depends('stage_id')
    def compute_stage_displayname(self):
        try:
            for rec in self:
                if rec.stage_id and rec.stage_id.name:
                    rec.stage_displayname = rec.stage_id.name
                else:
                    rec.stage_displayname = "None"
        except Exception:
            self.stage_displayname = "None"
    
    @api.depends('stage_id')
    def compute_is_readonly(self):
        if self.env.user.has_group('nbd_project.group_nbd_project_owner'):
            self.is_invisible_by_button = False
        else:
            self.is_invisible_by_button = True
        
        try:
            self.is_readonly_by_group = self.env.user.id != self.project_leader_id.id or self.stage_id.name == "Completed"
        except Exception:
            self.is_readonly_by_group = True
        
    is_invisible_prev = fields.Integer(string="是否可以点击上一步", compute='isinvisible_prev', store=False)
    
    is_invisible_next = fields.Integer(string="是否可以点击下一步", compute='isinvisible_next', store=False)
    
    stage_displayname = fields.Char(string="当前阶段名称", compute='compute_stage_displayname', store=False)
    
    is_invisible_by_button = fields.Boolean(string="隐藏其他阶段内容", store = False)
    
    is_readonly_by_group = fields.Boolean(string="判断当前用户是否可以编辑内容", store = False)

    # 阶段切换日志
    stage_change_log_ids = fields.One2many('nbd.project.task.stage.change.log',  'project_task_id', string='审批记录')
    
    # NDA 相关文件
    NDA_nbd_filemanager_ids = fields.One2many('nbd.filemanager', 'task_id', string='NDA 相关文件', domain=[('task_stage', '=', 'NDA')])
    
    # DD 尽职调查文件
    DD_nbd_filemanager_1_ids = fields.One2many('nbd.filemanager', 'task_id', string='DD 尽职调查文件', domain=[('task_stage', '=', 'DD_尽调')])
    
    # DD 其他文件
    DD_nbd_filemanager_2_ids = fields.One2many('nbd.filemanager', 'task_id', string='DD 其他文件', domain=[('task_stage', '=', 'DD_其它')])
    
    # Internal Review Business Case文档
    Internal_nbd_filemanager_1_ids = fields.One2many('nbd.filemanager', 'task_id', string='Business Case文档', domain=[('task_stage', '=', 'Business Case文档')])
    
    # Internal Review 会议纪要及其他文档
    Internal_nbd_filemanager_2_ids = fields.One2many('nbd.filemanager', 'task_id', string='IR 其它文档', domain=[('task_stage', '=', 'IR 其它文档')])
    
    # Contract Eflow合同
    Contract_nbd_filemanager_1_ids = fields.One2many('nbd.filemanager', 'task_id', string='Contract Eflow合同', domain=[('task_stage', '=', 'Contract_合同')])
    
    # Contract 其他文件
    Contract_nbd_filemanager_2_ids = fields.One2many('nbd.filemanager', 'task_id', string='Contract 其他文件', domain=[('task_stage', '=', 'Contract_其它')])
   
    # 获取下一个阶段
    @api.model
    def get_next_stage(self):
        current_stage_id = self.stage_id.id
        
        stages = self.env['project.task.type'].search([('project_ids', '=', self.project_id.id)])
        stages = stages.sorted(key=lambda x: x.sequence)  # 假设阶段有一个sequence字段来确定顺序

        current_index = stages.ids.index(current_stage_id)
        if current_index + 1 < len(stages.ids):
            next_stage_id = stages.ids[current_index + 1]
            next_stage = self.env['project.task.type'].browse(next_stage_id)
            return next_stage.display_name, next_stage.id
        else:
            return None, None  # 如果没有下一个阶段，返回None
        
    @api.model
    def get_prev_stage(self):
        current_stage_id = self.stage_id.id
        stages = self.env['project.task.type'].search([('project_ids', '=', self.project_id.id)])
        stages = stages.sorted(key=lambda x: x.sequence)  # 假设阶段有一个sequence字段来确定顺序

        current_index = stages.ids.index(current_stage_id)
        if current_index - 1 >= 0:
            next_stage_id = stages.ids[current_index - 1]
            next_stage = self.env['project.task.type'].browse(next_stage_id)
            return next_stage.display_name, next_stage.id
        else:
            return None, None  # 如果没有下一个阶段，返回None
    
    
    def action_back(self):
        prev_display,prev_id = self.get_prev_stage()
        if not prev_id:
            raise UserError("未找上一阶段主键，请检查当前所处阶段")
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'nbd.project.task.stage.change.log',
            'name': '360项目管理',
            'view_mode': 'form',
            'target': 'new',            
            'context': { 'project_task_id' : self.id,
                        'current_stage_id' : self.stage_id.id,
                        'current_stage_display_name' : self.stage_id.display_name,
                        'next_stage_id' : prev_id,
                        'next_stage_display_name' : prev_display,
                        }
        }
        
    def action_forward(self):
        next_display,next_id = self.get_next_stage()
        if not next_id:
            raise UserError("未找下一阶段主键，请检查当前所处阶段")
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'nbd.project.task.stage.change.log',
            'name': '360项目管理',
            'view_mode': 'form',
            'target': 'new',
            'context': { 'project_task_id' : self.id,
                        'current_stage_id' : self.stage_id.id,
                        'current_stage_display_name' : self.stage_id.display_name,
                        'next_stage_id' : next_id,
                        'next_stage_display_name' : next_display,
                        }
        }
        
    def action_add_nda_file(self):
        test = self
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'nbd.filemanager',
            'view_mode': 'form',
            'target': 'new',
            'context': { 'project_task_id' : self.id,
                        'task_stage' : self.stage_id.display_name,
                        }
        }
        
    def action_add_dd_1_file(self):
        test = self
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'nbd.filemanager',
            'view_mode': 'form',
            'target': 'new',
            'context': { 'project_task_id' : self.id,
                        'task_stage' : 'DD_尽调',
                        }
        }
        
    def action_add_dd_2_file(self):
        test = self
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'nbd.filemanager',
            'view_mode': 'form',
            'target': 'new',
            'context': { 'project_task_id' : self.id,
                        'task_stage' : 'DD_其它',
                        }
        }

    @api.depends('project_leader_id')
    def _compute_department_id(self):
        try:
            for record in self:
                if record.project_leader_id:
                    employee = self.env['hr.employee'].search([('user_id', '=', record.project_leader_id.id)],limit=1)
                    if employee:
                       if employee.department_id:
                        record.project_leader_dept = employee.department_id
                       else:
                           raise (exceptions.ValidationError("该人员部门未维护"))
        except ValueError as e:
            raise (exceptions.ValidationError("该人员部门未维护,请先维护部门信息"))

    @api.onchange('project_context')
    def _change_project_context(self):
        for record in self:
            if record.project_context:
                if len(record.project_context) > 500:
                    context = record.project_context
                    return {'warning': {
                        'title':("注意:"),
                        'message':("项目背景不能超过500个字符.")
                    }}

    @api.constrains('project_context')
    def _check_text_field_length(self):
        for record in self:
            if record.project_context:
                if len(record.project_context) > 500:
                    raise (exceptions.ValidationError("项目背景不能超过{}个字符".format(500)))

    @api.onchange('project_source')
    def _change_project_source(self):
        for record in self:
            if record.project_source:
                if len(record.project_source) > 20:
                    context = record.project_source
                    return {'warning': {
                        'title': ("注意:"),
                        'message': ("项目来源不能超过20个字符.")
                    }}
    @api.constrains('project_source')
    def _check_project_source_length(self):
        for record in self:
            if record.project_source:
                if len(record.project_source) > 20:
                    raise (exceptions.ValidationError("项目来源不能超过{}个字符".format(20)))
    @api.onchange('company_profile')
    def _change_company_profile(self):
        for record in self:
            if record.company_profile:
                if len(record.company_profile) > 512:
                    context = record.company_profile
                    return {'warning': {
                        'title': ("注意:"),
                        'message': ("公司简介不能超过512个字符.")
                    }}
    @api.constrains('company_profile')
    def _check_company_profile_length(self):
        for record in self:
            if record.company_profile:
                if len(record.company_profile) > 512:
                    raise (exceptions.ValidationError("公司简介不能超过{}个字符".format(512)))

    @api.onchange('business_value')
    def _change_business_value(self):
        for record in self:
            if record.business_value:
                if len(record.business_value) > 512:
                    context = record.business_value
                    return {'warning': {
                        'title': ("注意:"),
                        'message': ("业务价值不能超过512个字符.")
                    }}

    @api.constrains('business_value')
    def _check_business_value_length(self):
        for record in self:
            if record.business_value:
                if len(record.business_value) > 512:
                    raise (exceptions.ValidationError("业务价值不能超过{}个字符".format(512)))

    @api.onchange('expected_investment')
    def _change_expected_investment(self):
        for record in self:
            if record.expected_investment:
                if len(record.expected_investment) > 512:
                    context = record.expected_investment
                    return {'warning': {
                        'title': ("注意:"),
                        'message': ("预计投入不能超过512个字符.")
                    }}

    @api.constrains('expected_investment')
    def _check_expected_investment_length(self):
        for record in self:
            if record.expected_investment:
                if len(record.expected_investment) > 512:
                    raise (exceptions.ValidationError("预计投入不能超过{}个字符".format(512)))
    @api.onchange('main_risks')
    def _change_main_risks(self):
        for record in self:
            if record.main_risks:
                if len(record.main_risks) > 512:
                    context = record.main_risks
                    return {'warning': {
                        'title': ("注意:"),
                        'message': ("主要风险不能超过512个字符.")
                    }}
    @api.constrains('main_risks')
    def _check_main_risks_length(self):
        for record in self:
            if record.main_risks:
                if len(record.main_risks) > 512:
                    raise (exceptions.ValidationError("主要风险不能超过{}个字符".format(512)))

    @api.onchange('cooperation_model')
    def _change_cooperation_model(self):
        for record in self:
            if record.cooperation_model:
                if len(record.cooperation_model) > 512:
                    context = record.cooperation_model
                    return {'warning': {
                        'title': ("注意:"),
                        'message': ("合作模式不能超过512个字符.")
                    }}

    @api.constrains('cooperation_model')
    def _check_cooperation_model_length(self):
        for record in self:
            if record.cooperation_model:
                if len(record.cooperation_model) > 512:
                    raise (exceptions.ValidationError("合作模式不能超过{}个字符".format(512)))

    @api.constrains('main_contact_phone')
    def _check_main_contact_phone(self):
        for record in self:
            if record.main_contact_phone:
                if not (len(record.main_contact_phone) == 11 or len(record.main_contact_phone) == 10 or len(
                        record.main_contact_phone) == 0):
                    raise (exceptions.ValidationError("主要联系人电话只能为11位或10位"))

    @api.constrains('other_contact_phone')
    def _check_other_contact_phone(self):
        for record in self:
            if record.other_contact_phone:
                if not (len(record.other_contact_phone) == 11 or len(record.other_contact_phone) == 10 or len(
                        record.other_contact_phone) == 0):
                    raise (exceptions.ValidationError("其他联系人电话只能为11位或10位"))

    @api.constrains('unified_social_credit_code')
    def _check_unified_social_credit_code_length(self):
        for record in self:
            if record.unified_social_credit_code:
                # 检查是否只包含数字和大写字母
                if not (record.unified_social_credit_code.isalnum() and record.unified_social_credit_code.isupper()):
                    raise exceptions.ValidationError(("统一社会信用代码必须包含数字和大写字母."))
                # 检查长度是否为18位
                if len(record.unified_social_credit_code) != 18:
                    raise exceptions.ValidationError(("统一社会信用代码必须为18位."))
    def create(self, vals_list):
        record = super().create(vals_list)
        print("数据创建成功")
        self._insert_data_in_folder_table(record)
        return record

    def _insert_data_in_folder_table(self, record):
        task_id = record.id
        task_name = record.name
        task_type_ids = record.project_id.type_ids
        # 根据项目信息创建项目根目录
        root_folder = self.env['nbd.folder'].create({
            'task_id':task_id,
            'task_name':task_name,
            'name':task_name
        })
        print("文件夹创建成功")
        print(task_type_ids)
        for taskType in task_type_ids:
            childs_folder = self.env['nbd.folder'].create({
                'task_id': task_id,
                'task_name': task_name,
                'parent_id': root_folder.id,
                'description': taskType.disabled_rating_warning,
                'name': taskType.name
            })
            print("子文件夹创建成功")
